package com.iqik.client;

import com.iqik.handler.UserClientHandler;
import io.netty.bootstrap.Bootstrap;
import io.netty.channel.ChannelInitializer;
import io.netty.channel.ChannelOption;
import io.netty.channel.ChannelPipeline;
import io.netty.channel.EventLoopGroup;
import io.netty.channel.nio.NioEventLoopGroup;
import io.netty.channel.socket.SocketChannel;
import io.netty.channel.socket.nio.NioSocketChannel;
import io.netty.handler.codec.string.StringDecoder;
import io.netty.handler.codec.string.StringEncoder;

import java.lang.reflect.InvocationHandler;
import java.lang.reflect.Method;
import java.lang.reflect.Proxy;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

public class RPCClient {

    // 1. 创建一个线程池对象，处理自定义事件
    private static ExecutorService executorService =
            Executors.newFixedThreadPool(Runtime.getRuntime().availableProcessors());
    // 2。声明一个自定义事件处理器
    private static UserClientHandler userClientHandler;

    //3。初始化客户端，（创建连接池，bootstrap 设置bootstrap 连接服务器）
    public static void initClient() throws InterruptedException {
        // 初始化user client handler
        userClientHandler = new UserClientHandler();
        // 创建连接池对象
        EventLoopGroup group = new NioEventLoopGroup();
        // 创建客户端引导类
        Bootstrap bootstrap = new Bootstrap();
        // 配置启动引导类
        bootstrap.group(group)
                // 设置通道为NIO
                .channel(NioSocketChannel.class)
                // 设置请求协议为TCP
                .option(ChannelOption.TCP_NODELAY, true)
                // 监听channel并初始化
                .handler(new ChannelInitializer<SocketChannel>() {
                    @Override
                    protected void initChannel(SocketChannel socketChannel) throws Exception {
                        // 获取channel pipeline
                        ChannelPipeline pipeline = socketChannel.pipeline();

                        pipeline.addFirst(new StringEncoder());
                        pipeline.addLast(new StringDecoder());
                        // 添加自定义事件处理器
                        pipeline.addLast(userClientHandler);
                    }
                });
        // 连接服务端
        bootstrap.connect("127.0.0.1", 8201).sync();
    }

    /**
     *  4。使用jdk动态代理创建对象
     * @param clazz     根据类名，生成自类对象
     * @param providerParam "CLAZZ#METHOD#PARAMS"
     * @return
     */
    public static Object createPoxy(Class<?> clazz, final String providerParam) {
        return Proxy.newProxyInstance(Thread.currentThread().getContextClassLoader(),
                new Class[]{clazz}, new InvocationHandler() {
                    @Override
                    public Object invoke(Object proxy, Method method, Object[] args) throws Throwable {
                        // 初始化客户端，
                        if (userClientHandler == null) initClient();
                        //设置UserClientHandler参数
                        userClientHandler.setParam(providerParam + args[0]);
                        // 使用线程池，开启线程处理call写操作，
                        return executorService.submit(userClientHandler).get();
                    }
                });
    }

}
